#include "myhead.h"
#include "ts.h"

#define TEMPERATURE_COLOR 0xFFFF00
#define HUMIDITY_COLOR	  0xFF0000
// #define LINE_WIDTH		  3	


volatile int out_flag;

void *detect_exit_sig(void *arg)
{
	struct coordinate coor;
	bool released;
	while(1)
	{
		ts_trace(ts_fd, &coor, &released);
		if (released && coor.x>770 && coor.y<35)
		{
			out_flag = 0;
			return NULL;
		}
	}
}

void get_humi_coor(int *y, int humidity)
{
	*y = 442 - (int)(3.8*humidity);

	if (*y > 442 || *y < 62)
	{
		printf("error coor\n");
	}
}

void get_temp_coor(int *y, int temp)
{
	*y = 442 - (int)(1.9*(temp-200));

	if (*y > 442 || *y < 62)
	{
		printf("error coor\n");
	}
}

void temperature(void)
{
	int dht11_fd = open("/dev/dht11_dev",O_RDWR);
	if (dht11_fd < 0)
	{
		perror("open deht11 failed");
		return;
	}
	out_flag = 1;
	pthread_t tid;
	pthread_create(&tid, NULL, detect_exit_sig, NULL);
	pthread_detach(tid);

	int i;
	int humidity;	//湿度 单位%
	int temp;		//温度 单位0.1℃
	int container;

	struct coordinate old_coor_humi;
	struct coordinate new_coor_humi;
	struct coordinate old_coor_temp;
	struct coordinate new_coor_temp;

	//得到初始坐标
	while(read(dht11_fd, &container, 4) == 4)
	{
		temp = ((container>>8)&(0xff))*10 + (container&(0xff));
		humidity = (container >> 24) & (0xff);  
	}
	get_humi_coor(&(old_coor_humi.y), humidity);
	get_temp_coor(&(old_coor_temp.y), temp);

	while(out_flag)
	{
		lcd_draw_jpg(0, 0, "./jpeg/temperature.jpg", NULL, 0, 0);
		old_coor_humi.x = 43;
		old_coor_temp.x = 43;

		for (i = 0; i < 10 && out_flag; ++i)
		{
			//读取温湿度值
			while(read(dht11_fd, &container, 4) == 4)
			{
				temp = ((container>>8)&0xff)*10 + (container&0xff);
				humidity = (container >> 24) & (0xff);  
				printf("temp = %d, humidity = %d\n", temp, humidity);
			}

			//========
			new_coor_humi.x = 43+71*(i+1);
			new_coor_temp.x = 43+71*(i+1);
			get_humi_coor(&(new_coor_humi.y), humidity);
			get_temp_coor(&(new_coor_temp.y), temp);

			// printf("[old]x = %d, [old]y = %d\n",old_coor_temp.x, old_coor_temp.y);
			// printf("[new]x = %d, [new]y = %d\n",new_coor_temp.x, new_coor_temp.y);
			lcd_draw_line(old_coor_temp.x, old_coor_temp.y,
						  new_coor_temp.x, new_coor_temp.y, 
						  	TEMPERATURE_COLOR);

			lcd_draw_line(old_coor_humi.x, old_coor_humi.y,
						  new_coor_humi.x, new_coor_humi.y, 
						  	HUMIDITY_COLOR);

			old_coor_temp = new_coor_temp;
			old_coor_humi = new_coor_humi;
			sleep(3);
		}
	}
}